package com.yuexun.beilunpatient.ui.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.AppContext;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.bean.BaseListEntity;
import com.yuexun.beilunpatient.ui.login.bean.LoginBean;
import com.yuexun.beilunpatient.ui.login.bean.UserDtlBean;
import com.yuexun.beilunpatient.ui.login.model.impl.LoginModel;
import com.yuexun.beilunpatient.ui.login.presenter.impl.LoginPresenter;
import com.yuexun.beilunpatient.ui.login.presenter.impl.UserDtlPresenter;
import com.yuexun.beilunpatient.ui.login.ui.view.ILoginView;
import com.yuexun.beilunpatient.ui.login.ui.view.IUserDtlView;
import com.yuexun.beilunpatient.ui.main.ui.MainActivity;
import com.yuexun.beilunpatient.widget.ToastDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseKJActivity implements ILoginView,IUserDtlView {

    @Bind(R.id.username_edit)
    EditText usernameEdit;
    @Bind(R.id.password_edit)
    EditText passwordEdit;

    LoginPresenter presenter;
    UserDtlPresenter userDtlPresenter;
    ToastDialog dialog;
    String device_token;
    PushAgent mPushAgent;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter = new LoginPresenter(new LoginModel(), this);
        userDtlPresenter = new UserDtlPresenter(new LoginModel(),this);
        AppContext appContext = (AppContext) getApplicationContext();
        mPushAgent = appContext.mPushAgent;
        device_token = mPushAgent.getRegistrationId();
        PushAgent.getInstance(aty).onAppStart();

        Boolean islogin = PreferenceHelper.readBoolean(this, AppConfig.USER_INFO, AppConfig.ISLOGIN);
        if (islogin) {
            usernameEdit.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.USERNAME_LOGIN));
            passwordEdit.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.USERPWD));
        }
        else {
//            usernameEdit.setText("330624199307185229");
//            usernameEdit.setText("330206198509183412");
//            passwordEdit.setText("123456");
        }
    }

    private void login() {
        if (usernameEdit.getText().toString().isEmpty()) {
            ViewInject.toast("请输入账号");
            return;
        }
        if (passwordEdit.getText().toString().isEmpty()) {
            ViewInject.toast("请输入密码");
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("idCard", usernameEdit.getText().toString());
        params.put("password", passwordEdit.getText().toString());
        if (TextUtils.isEmpty(device_token)) {
            device_token = AppContext.device_token;
        }
        params.put("deviceToken", device_token);
        params.put("appKey", "Android");
        presenter.dologin(params);

        dialog = new ToastDialog(aty, "正在登录，请稍后");
        dialog.show();
    }

    @OnClick({R.id.login, R.id.register, R.id.forget_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login:
                login();
                break;
            case R.id.register:
                startActivity(new Intent(this, Act_Register.class));
                break;
            case R.id.forget_password:
                startActivity(new Intent(this, Act_Forget_Psw.class));
                break;
            default:
                break;
        }
    }

    /**
     * 获取用户详情
     */
    private void loadUsrInfo(){
        Map<String, String> params = new HashMap<>();
        params.put("patientId", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.PATIENT_ID));
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        userDtlPresenter.loadPatientInfoDetail(params);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doInLogin(BaseListEntity<LoginBean> loginBean) {
        dialog.dismiss();
        if (loginBean.getStatus().equals("200")) {
            if(loginBean.getDatas().get(0).getCode().equals("1")){
                String filename = AppConfig.USER_INFO;
                PreferenceHelper.write(aty, filename, AppConfig.PICTURE_UUID, loginBean.getDatas().get(0).getPictureUuid());
                PreferenceHelper.write(aty, filename, AppConfig.SESSION_ID, loginBean.getDatas().get(0).getSessionUuid());
                PreferenceHelper.write(aty, filename, AppConfig.ID_CARD, usernameEdit.getText().toString());
                PreferenceHelper.write(aty, filename, AppConfig.USER_NAME, loginBean.getDatas().get(0).getUserName());
                PreferenceHelper.write(aty, filename, AppConfig.PATIENT_ID, loginBean.getDatas().get(0).getPatientId());

                // 自动账号登入
                PreferenceHelper.write(aty, filename, AppConfig.ISLOGIN, true);
                PreferenceHelper.write(aty, filename, AppConfig.USERNAME_LOGIN, usernameEdit.getText().toString());
                PreferenceHelper.write(aty, filename, AppConfig.USERPWD, passwordEdit.getText().toString());
                PreferenceHelper.write(aty, filename, AppConfig.USERDEVICE, device_token);
                PreferenceHelper.write(aty, filename, AppConfig.USERAPPKEY, "Android");

                mPushAgent.addAlias(loginBean.getDatas().get(0).getPatientId() + "", "PATIENT_ID", new UTrack.ICallBack() {
                    @Override
                    public void onMessage(boolean isSuccess, String message) {
                        Log.i("jx", message);
                    }
                });

                loadUsrInfo();
            }else{
                ViewInject.toast(loginBean.getDatas().get(0).getDescription());
            }

        }else{
            ViewInject.toast(loginBean.getMessage());
        }
    }

    @Override
    public void fail() {
        dialog.dismiss();
    }

    @Override
    public void loadPatientInfoDetail(BaseListEntity<UserDtlBean> entity) {
        if(entity.getStatus().equals("200")){
            String filename = AppConfig.USER_INFO;
            PreferenceHelper.write(aty, filename, AppConfig.TEL, entity.getDatas().get(0).getMobile());
            PreferenceHelper.write(aty, filename, AppConfig.HEALTHID, entity.getDatas().get(0).getHealthNo());
            if(entity.getDatas().get(0).getSex() == 1){
                PreferenceHelper.write(aty, filename, AppConfig.SEX, "男");
            }else if(entity.getDatas().get(0).getSex() == 2){
                PreferenceHelper.write(aty, filename, AppConfig.SEX, "女");
            }else {
                PreferenceHelper.write(aty, filename, AppConfig.SEX, "不详");
            }

            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
        else {
            ViewInject.toast("个人详情获取失败:"+entity.getMessage());
        }
    }
}
